﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DigitalRune.Windows.Docking;
using CalemShop.Classes;
using System.Collections;

namespace CalemShop.Forms
{
    public partial class FrmCustomerExplorer : FrmBaseDock
    {
        internal delegate void ShowAndUpdateProgressWaitingDlg(bool visible, int percent);

        public FrmCustomerExplorer()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            backgroundWorker1.RunWorkerAsync();
        }

        public FrmCustomerExplorer(FrmCalemShop shop)
            : base(shop)
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            backgroundWorker1.RunWorkerAsync();
        }

        private void LoadCustomerList()
        {
            try
            {
                ShowWaitingDialog(true, 0);
                DataTable t = DataManager.GetAllCustomer();
                backgroundWorker1.ReportProgress(10);
                if (t != null && t.Rows.Count > 0)
                {
                    ListViewItem item = null;
                    ListViewItem[] list = new ListViewItem[t.Rows.Count];
                    int index = 0;
                    int percentage = 0;
                    foreach (DataRow r in t.Rows)
                    {
                        int point = 0;
                        if (r["point"] != null)
                        {
                            int.TryParse(r["point"].ToString(), out point);
                        }

                        string customerName = (string)r["customerName"];
                        string formatName = FormatCustomerName(customerName);
                        item = new ListViewItem(new string[] {
                        formatName , (string)r["phone"], point.ToString(), (string)r["serial"]
                        });

                        item.SubItems[clPhone.Index].Tag = customerName;
                        item.Tag = r["customerId"];
                        item.ImageIndex = 0;
                        list[index] = item;
                        index++;
                        percentage = (index * 100) / list.Length;
                        ShowWaitingDialog(true, percentage);
                    }

                    listCustomer.Items.AddRange(list);
                    listCustomer.Refresh();
                    listCustomer.Focus();
                    listCustomer.Items[0].Selected = true;
                    backgroundWorker1.ReportProgress(percentage);

                }
            }
            catch (Exception ee)
            {
                ShowWaitingDialog(false, 0);
                Reporter.WriteErrorEx(ee);
            }
        }

        public static string FormatCustomerName(string name)
        {
            try
            {
                if (string.IsNullOrEmpty(name))
                {
                    return name;
                }

                name = name.Trim();
                string[] words = name.Split(' ');
                StringBuilder text = new StringBuilder(words[words.Length - 1]);
                text.Append(" - ").Append(name);
                return text.ToString().ToUpper();
            }
            catch (Exception e)
            {
                return e.Message;
            }

        }

        private void DoWorkLoadCustomerList(object sender, DoWorkEventArgs e)
        {
            LoadCustomerList();
        }

        private void DoProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ShowWaitingDialog(true, e.ProgressPercentage);
        }

        private void DoProgressCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ShowWaitingDialog(false, 0);
        }

        private void ShowWaitingDialog(bool visible, int pecentage)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new ShowAndUpdateProgressWaitingDlg(ShowWaitingDialog), visible, pecentage);

            }
            else
            {
                if (visible)
                {
                    if (panelWaiting.Visible == false)
                    {
                        panelWaiting.Visible = true;
                        int x = (this.Width - panelWaiting.Width) / 2;
                        int y = (this.Height - panelWaiting.Height) / 2;
                        panelWaiting.Location = new Point(x, y);
                        panelWaiting.Refresh();
                    }

                    if (pecentage <= 100)
                    {
                        progressBar1.Value = pecentage;
                    }
                }
                else
                {
                    progressBar1.Value = 0;
                    panelWaiting.Visible = false;
                    panelWaiting.Refresh();
                }
            }
        }

        private void btAdd_Click(object sender, EventArgs e)
        {
            FrmAddNewCustomer frm = new FrmAddNewCustomer();
            frm.StartPosition = FormStartPosition.CenterScreen;
            if (frm.ShowDialog(this) == DialogResult.OK)
            {
                ListViewItem item = frm.NewCustomerView;
                if (item != null)
                {
                    this.listCustomer.Items.Add(item);
                    listCustomer.EnsureVisible(item.Index);
                }

                for (int i = 0; i < listCustomer.Items.Count; i++)
                {
                    if (listCustomer.Items[i].Equals(item))
                    {
                        listCustomer.Items[i].Selected = true;
                        listCustomer.EnsureVisible(i);
                        break;
                    }
                }
            }
        }

        private void listCustomer_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                e.SuppressKeyPress = false;
                DoDeleteCustomer();
            }
        }

        private void DoDeleteCustomer()
        {
            if (listCustomer.SelectedItems != null && listCustomer.SelectedItems.Count > 0)
            {
                try
                {
                    ArrayList removeList = new ArrayList();
                    for (int i = 0; i < listCustomer.SelectedItems.Count; i++)
                    {
                        ListViewItem item = listCustomer.SelectedItems[i];
                        if (item.Tag != null)
                        {
                            if (MessageBox.Show(this, string.Format("Bạn muốn xóa [{0}] này khỏi hệ thống ?", item.Text), "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                            {
                                int cid = 0;
                                int.TryParse(item.Tag.ToString(), out cid);
                                if (DataManager.DeleteCustomer(cid))
                                {
                                    removeList.Add(item);
                                }
                            }
                        }
                    }

                    for (int i = 0; i < removeList.Count; i++)
                    {
                        listCustomer.Items.Remove((ListViewItem)removeList[i]);
                    }
                }
                catch (Exception e)
                {
                    Reporter.WriteErrorEx(e);
                }

            }

        }

        private void listCustomer_DoubleClick(object sender, EventArgs e)
        {
            ListViewItem item = null;
            if (listCustomer.SelectedItems.Count > 0)
            {
                item = listCustomer.SelectedItems[0];
            }

            if (item != null)
            {
                FrmAddNewCustomer frm = new FrmAddNewCustomer();
                frm.StartPosition = FormStartPosition.CenterScreen;
                frm.EditMode = true;
                frm.NewCustomerView = item;
                frm.ShowDialog(this);
                //if (frm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                //{
                //    for (int i = 0; i < listCustomer.Items.Count; i++)
                //    {
                //        if (frm.NewCustomerView != null && listCustomer.Items[i].Equals(item))
                //        {
                //            listCustomer.Items[i] = frm.NewCustomerView;
                //            listCustomer.Items[i].Selected = true;
                //            listCustomer.EnsureVisible(i);
                //            break;
                //        }
                //    }
                //}
            }
        }

    } // class
}
